package com.esb.bootstrap;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import com.esb.transport.handler.DefaultHandler;
import com.esb.transport.handler.codec.MessageDecoder;
import com.esb.transport.handler.codec.MessageEncoder;
import com.esb.transport.protocal.FastjsonCodec;
import com.esb.transport.protocal.ServiceDispatcher;
import com.esb.utils.ConfigUtils;
import com.esb.utils.Constants;

public class Server implements Protocol {
	
	public Object exportService(Class<?> serviceClazz){
		if(serviceClazz.isInterface())throw new RuntimeException("不能将接口导出为服务!");
		try {
			return exportService(serviceClazz.newInstance());
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Object exportService(Object service){
		ServiceDispatcher.register(service);
		return service;
	}
	
	public void start() throws Exception{
		// Configure the server.
		ServerBootstrap b = new ServerBootstrap();
        b.group(new NioEventLoopGroup(), new NioEventLoopGroup())
         .channel(NioServerSocketChannel.class)
         //.option(ChannelOption.SO_BACKLOG, 100)
         .localAddress(ConfigUtils.getProperty(Constants.PROPERTIES_KEY_PORT, 8888))
         //.childOption(ChannelOption.TCP_NODELAY, true)
         .childHandler(new ChannelInitializer<SocketChannel>() {
             @Override
             public void initChannel(SocketChannel ch) throws Exception {
            	 ch.pipeline().addLast(
            			 	new MessageEncoder(new FastjsonCodec()),
                            new MessageDecoder(new FastjsonCodec()),
                            new LoggingHandler(LogLevel.INFO), 
                            new DefaultHandler());
             }
         });
        // Start the server.
		b.bind().sync();
		// Wait until the server socket is closed.
	}
	
	public void shutdown(){
		
	}
}
